//
//  SSHomeViewController.swift
//  拾舍清洁
//
//  Created by sky.wei on 2023/2/6.
//

import UIKit
import Alamofire
import SwiftyJSON

class SSHomeViewController: UIViewController, UIImagePickerControllerDelegate & UINavigationControllerDelegate {
    
    ///优惠券数据
    var items: Array<ListItemCombo> = []
    
    @IBOutlet weak var tableView: UITableView!

    override func viewDidLoad() {
        super.viewDidLoad()
        

        setupUIs()
        getBannerNetwork()
        getListNetwork()
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        tableView.reloadData()
    }
    
    func setupUIs() {
        rightNav()
        tableView.tableHeaderView = headerView
        tableView.register(UINib(nibName: "SSHomeTableViewCell", bundle: Bundle.init(for: SSHomeTableViewCell.self)), forCellReuseIdentifier: "SSHomeTableViewCell")
        tableView.delegate = self
        tableView.dataSource = self
        tableView.separatorStyle = .none
        self.tableView.es.addPullToRefresh {
            [unowned self] in
            self.tableView.es.stopPullToRefresh()
           getBannerNetwork()
            getListNetwork()
        }
    }
    
    override func viewDidLayoutSubviews() {
        super.viewDidLayoutSubviews()
        headerView.frame = CGRect(x: 0, y: 0, width: UIScreen.main.bounds.size.width, height: 530 + 40)

    }
    
    func rightNav() {
        let btn = UIButton(frame: CGRect(x: 0, y: 0, width: 20, height: 20))
        btn.setImage(UIImage(named: "headset_nav"), for: .normal)
        btn .addTarget(self, action: #selector(rightNavAcion), for: .touchUpInside)
        let rightItem = UIBarButtonItem(customView: btn)
        self.navigationItem.rightBarButtonItem = rightItem
    }
    
    @objc func rightNavAcion(){
        navigationController?.pushViewController(SSWorkContentController(), animated: true)
        
//        navigationController?.pushViewController(SSNormalDetailController(), animated: true)
//        navigationController?.present(SSGetCouponViewController(), animated: true)
//        navigationController?.present(SSNormalTimeViewController(), animated: true)
        
//        pushViewController(SSGetCouponViewController(), animated: true)
    }
    
    //MARK: -lazy
    lazy var headerView: SSHomeHeaderView = {
        let headerView = SSHomeHeaderView.homeHeaderView()
        headerView.delegate = self
        return headerView
    }()
    
    @IBAction func shoppingcartAction(_ sender: Any) {
        if !kIsLogin {
            kNotifiDefault.post(name: .AppShowLoginController, object: nil)
            return
        }
        let vc = SSUserOrderViewController.init(nibName: "SSUserOrderViewController", bundle: nil)
        navigationController?.pushViewController(vc, animated: true)

    }
    //MARK: -networing
    //list
    func getListNetwork() {
        
        let param = [
            "parentId": "2",
            "type" : "1"
        ] as [String:AnyObject]
        SSProductRequest.getProductRequest(parameters: param) { items in
            self.items = items
            self.tableView.reloadData()
        }
       
    }
    //banner
    func getBannerNetwork() {
        HttpConnectTools.share.request(urlString: APIUrl.share.getCouponItem_URL, parameters: nil) { (result, error) in
            if let _ = result{
                let json = JSON(parseJSON: result!)
                let data = json["data"]["listCoupon"].arrayValue
                let items : SSBannerViewModel = SSBannerViewModel.deserialize(from: result, designatedPath: "data") ?? SSBannerViewModel()
                debugPrint("----------",items as Any)
                print("---data\(data)")
                self.headerView.setbanners(banners: items.listCoupon)
            }else{
            }
        }
    }
    
    //banner
    func getAddCouponNetwork(id:String) {
        let param = [
            "couponId": id,
            "phoneNo": kUserPhone
        ]as[String:AnyObject]
        SSProgressHUD.share.show()
        HttpConnectTools.share.request(urlString: APIUrl.share.addCoupon_URL, parameters: param) { (result, error) in
            SSProgressHUD.share.dismiss()
            if let _ = result{
                let json = JSON(parseJSON: result!)

               let view = SSGetCouponDoneView.couponDoneView()
                view.numberResult {
                    let vc = SSMyCouponController.init()
                    self.navigationController?.pushViewController(vc, animated: true)
                }

//                UIViewController.current().view.makeToast(json["retMsg"].string)
            }else{
                if let message = error?.userInfo["errorinfo"]{
                    UIViewController.current().view.makeToast(message as? String)
                }
            }
        }
    }
}


//MARK: -delegate
extension SSHomeViewController:SSHomeHeaderViewDelegate{
    func didSelectItem(index: Int) {
//        btnRecord()

        if !kIsLogin {
            kNotifiDefault.post(name: .AppShowLoginController, object: nil)
            return
        }
        if(index == 1){
            navigationController?.pushViewController(SSNormalCleanViewController(), animated: true)
        }else if(index == 3||index == 4){
            let vc = SSCleanDetailController.init(nibName: "SSCleanDetailController", bundle: nil)
            vc.typeID = index
            navigationController?.pushViewController(vc, animated: true)
        }else if(index == 2){
            let vc = SSCheckoutCleanPageViewController.init(nibName: "SSCheckoutCleanPageViewController", bundle: nil)
            navigationController?.pushViewController(vc, animated: true)
        }
   
    }
    func didADSelectItem(index: Int) {
        if !kIsLogin {
            kNotifiDefault.post(name: .AppShowLoginController, object: nil)
            return
        }
        let banner:SSBanner = self.headerView.bannerDatas[index-1] as! SSBanner
        let alertView = EtcAlertView(title:"领取优惠券", message: "您是否要领取优惠券", cancleTitle:"取消", confirmTitle: "确定")
        alertView.showAlert(confirm:  {
            self.getAddCouponNetwork(id: banner.id)
        }) {
        }
    }
    
}

extension SSHomeViewController: UITableViewDelegate, UITableViewDataSource
{
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
//        let item :ListCombo =  self.items[indexPath.section].listCombos[indexPath.row] as! ListCombo
//        let vc =  SSItemDetailViewController.init(nibName: "SSItemDetailViewController", bundle: nil)
//        vc.id = item.id
//        present(vc, animated: true)
    }
    func numberOfSections(in tableView: UITableView) -> Int {
        return self.items.count
    }
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 24 + 16 + 6
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return items[section].listCombos.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "SSHomeTableViewCell") as! SSHomeTableViewCell
        cell.setType(type: "2")
        cell.setData(self.items[indexPath.section].listCombos[indexPath.row] as! ListCombo)
        return cell
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
         let item = self.items[indexPath.section].listCombos[indexPath.row] as! ListCombo
        return item.cellHeight
//        return 170
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        var title = ""
        if self.items.count > 0 {
            title = (self.items[section] ).name
        }
        let view = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 24 + 16 + 6))
        view.backgroundColor = UIColor.white
        
        let sectionView = UIView(frame: CGRect(x: 0, y: 0, width: tableView.frame.width, height: 6))
        sectionView.backgroundColor = UIColor.init(hex: "#e5e5e5")
        view.addSubview(sectionView)
        
        
        let label = UILabel()
        label.text = title
        label.font = UIFont.systemFont(ofSize: 18, weight: .bold)
        label.textColor = UIColor.black
        view.addSubview(label)
        label.snp.makeConstraints { make in
            make.width.equalTo(150)
            make.height.equalTo(26)
            make.centerY.equalTo(view.frame.size.height/2 + 16)
            make.left.equalTo(16)
        }
        return view
    }
}


